package com.lyl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyl.domain.WorkIssue;
import com.lyl.dto.UserDto;
import com.lyl.feign.UserServiceFeign;
import com.lyl.mapper.WorkIssueMapper;
import com.lyl.service.WorkIssueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author lylbell
 * @date 2021-06-22 13:31
 */
    
@Service
public class WorkIssueServiceImpl extends ServiceImpl<WorkIssueMapper, WorkIssue> implements WorkIssueService {


    @Autowired
    private UserServiceFeign userServiceFeign;

    /**
     * 分页查找客服工单
     *
     * @param page
     * @param status
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public Page<WorkIssue> getByPage(Page<WorkIssue> page, Integer status, String startTime, String endTime) {
        Page<WorkIssue> pageData = page(page, new LambdaQueryWrapper<WorkIssue>()
                .between(!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime), WorkIssue::getCreated, startTime, endTime + " 23:59:59")
                .eq(status != null, WorkIssue::getStatus, status)
        );
        if (CollectionUtils.isEmpty(pageData.getRecords())) {
            return pageData;
        }
        //获取用户ids
        List<Long> userIds = pageData.getRecords().stream().map(WorkIssue::getUserId).collect(Collectors.toList());
        Map<Long, UserDto> basicUsers = userServiceFeign.getBasicUsers(userIds, null, null);
        if (CollectionUtils.isEmpty(basicUsers)) {
            return pageData;
        }

        //小技巧，将list转化成map（id，userDto）,在feign中已经重写了
//        Map<Long, UserDto> collect = basicUsers.stream().collect(Collectors.toMap(userDto -> userDto.getId(), userDto -> userDto));
        //将userDto中的数据添加到客服工单里边
        pageData.getRecords().forEach(workIssue -> {
            UserDto userDto = basicUsers.get(workIssue.getUserId());
            if (userDto != null) {
                workIssue.setUsername(userDto.getUsername());
                workIssue.setRealName(userDto.getRealName());
            }
        });
        return pageData;
    }
}
